package cmdServer

import (
	"SortSet/sortset"
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"
)

var s *sortset.SortSet

var commands []command

func init() {
	// 初始化sortSet
	s = sortset.NewSortSet()

	commands = make([]command, 0)
	// 添加help指令
	commands = append(commands, helpCommand)
	// 输入data指令
	commands = append(commands, dataCommand)
	// 添加add 指令
	commands = append(commands, addCommand)
	// 添加remove指令
	commands = append(commands, removeCommand)
	// 添加sub指令
	commands = append(commands, subCommand)
	// 添加count指令
	commands = append(commands, countCommand)
	// 添加intersection指令
	commands = append(commands, intersectionCommand)
	// 添加Difference指令
	commands = append(commands, differenceCommand)
	// 添加Union指令
	commands = append(commands, unionCommand)
	// 添加exit指令
	commands = append(commands, exitCommand)
}

// 运行cmd 客户端
func Run() {
	welcome()
	accpet()
}

// 打印欢迎信息
func welcome() {
	fmt.Println("进入CMD模式")
	helpCommand.process("", nil)
}

// 接受输入并且返回信息
func accpet() {
	<-time.After(200 * time.Millisecond)
	fmt.Println()
	fmt.Print("> ")
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		input := scanner.Text()
		input = strings.TrimSpace(input)
		output := executeCmd(input)
		if output != "" {
			fmt.Println(output)
		}
		fmt.Print("> ")
	}
}

// 执行指令
func executeCmd(str string) string {
	for _, v := range commands {
		if v.canProcess(str) {

			return v.process(str, s)
		}
	}
	return "noknow command, you can input 'help' for more message"
}
